<template>
	<scroll-view class="time-line-wrap">
		<view class="time-line">
			<view class="time-line-title">
			</view>
			<view class="up-arrow">
			</view>
			<view class="time-line-dashed">
			</view>
			<view class="time-line-container" :class="addTypeClass">
				<view class="time-line-list">
					<u-loading-icon style="padding: 200px 0 400rpx 5%;" vertical :show="isLoad&&timeLineList.length==0"
						text="加载中" textSize="18"></u-loading-icon>
					<view class="time-line-info" :key="index" :class="[layoutClass(index)]" :id="'timeline'+index"
						v-for="(item,index) of timeLineList">
						<view class="line-info-content">
							<view class="line-on-round"
								:style="{ opacity: current[index]&&[index].is=='ok'?1:1,top:'13px',left:'5px'}"
								:class="current[index]&&[index].is=='ok'?comeani:''"></view>
							<view class="line-on-round-line"
								:style="{ opacity: current[index]&&[index].is=='ok'?1:1,top:'20px',left:'22px'}"
								:class="current[index]&&[index].is=='ok'?comeani:''"></view>

							<view class="info-content-wrap" :style="{ opacity: current[index]&&[index].is=='ok'?1:1}"
								:class="current[index]&&[index].is=='ok'?comeani:''">
								<view class="info-title">
									{{item.title}}
								</view>

								<view class="info-content" @click.stop="onDetail(item,false)">
									<view class="options-trigger" v-if="item.userId==$store.state.userInfo.userId"
										@click.stop="openOptionsMenu(item)">
										<u-icon name="more-dot-fill" size="20" color="#666"></u-icon>
									</view>
									<view class="info-head">
										<view class="city">
											<u-icon name="map" size="20" color="#139AE0"></u-icon>
											<view class="name">{{item.province}}</view>
											<view class="small">{{getLocation(item.cityName)}}</view>
										</view>
									</view>
									<view class="info-txt">
										<PostShrink :size="24" :ellipsisBack="'rgb(232,232,238,.9)'" :line="3"
											:text="item.content"></PostShrink>
									</view>
									<view class="image-box">
										<view
											v-if="item.imageList && item.imageList.length > 0 && item.imageList[0].isImage==1">
											<view v-if="item.imageList.length === 4" class="grid-tianzi">
												<view v-for="(file, fileIndex) in item.imageList" :key="fileIndex"
													class="grid-tianzi-item"
													@click.stop="previewImage(item.imageList, fileIndex)">
													<u-image :src="file.fileUrl" width="85" height="85"
														mode="aspectFill" :lazy-load="true"></u-image>
												</view>
											</view>
											<u-album v-else :urls="item.imageList" :keyName="'fileUrl'" :multipleSize="85" :singleSize="180" :space="4"
												:lazy-load="true"></u-album>
										</view>
										<!-- #ifdef APP-PLUS || H5 -->
										<view :class="'video-wrapper-' + index" class="video-container-wrapper"
											v-if="item.imageList && item.imageList.length > 0 && item.imageList[0].isImage==0">
											<DomVideoPlayer :class="'video-'+index" :ref="'allPostRef'+index"
												:src="item.imageList[0].fileUrl" loop :muted="true" :autoplay="false"
												:isLoading="true" style="max-width: 600rpx;width:400rpx;"
												@click.native.stop="openCustomFullScreenVideo(index, item.imageList[0].fileUrl)" />
										</view>
										<!-- #endif -->
									</view>
									<view class="person">
										<view class="label">
											同行人：
										</view>
										<PersonShrink class="name-line-box" :item="item"></PersonShrink>
									</view>
									<view class="" style="border-bottom: 1rpx solid #E4E8E5;margin-top: 30rpx;">
									</view>
									<CommonPostActions :data="item" @onDetail="onDetail"></CommonPostActions>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<u-action-sheet :show="showOptionsMenu" :actions="optionsActions" cancelText="取消" @select="handleOptionSelect"
			@close="showOptionsMenu = false" :closeOnClickOverlay="true" :closeOnClickAction="true"></u-action-sheet>

		<u-action-sheet :show="showPermissionsMenu" :actions="permissionsActions" cancelText="取消"
			@select="handlePermissionSelect" @close="showPermissionsMenu = false" :closeOnClickOverlay="true"
			:closeOnClickAction="true"></u-action-sheet>

		<!-- 添加全屏视频模态框 -->
		<!-- #ifdef APP-PLUS || H5 -->
		<VideoFullscreenModal :visible="showVideoModal" :video-src="currentModalVideoSrc" 
			@close="closeCustomFullScreenVideo" />
		<!-- #endif -->
	</scroll-view>
</template>

<script>
	import PostShrink from "@/components/post-shrink/post-shrink.vue"
	import CommonPostActions from '@/components/common-post-actions/common-post-actions.vue';
	import PersonShrink from "@/components/person-shrink/person-shrink.vue"
	import {
		deletePost
	} from '@/request/api.js'
	// #ifdef APP-PLUS || H5
	import DomVideoPlayer from '@/components/DomVideoPlayer/DomVideoPlayer.vue'
	import VideoFullscreenModal from '@/components/VideoFullscreenModal/VideoFullscreenModal.vue'
	// #endif
	export default {
		components: {
			CommonPostActions,
			PersonShrink,
			PostShrink,
			// #ifdef APP-PLUS || H5
			DomVideoPlayer,
			VideoFullscreenModal
			// #endif
		},
		data() {
			return {
				HEIGHT: 0,
				result: [],
				current: [],
				sum: 0,
				comeani: 'come-ani',
				isScroll: true,
				expanded: false,
				showExpand: false,
				showOptionsMenu: false,
				showPermissionsMenu: false,
				currentItem: null,
				showVideoModal: false,
				currentModalVideoSrc: '',
				currentModalVideoId: null,
				optionsActions: [{
						name: '删除',
						action: 'delete',
						color: '#FF0000',
						fontSize: '16px'
					},
					{
						name: '编辑',
						action: 'edit',
						fontSize: '16px'
					},
					{
						name: '设置权限',
						action: 'setPermissions',
						fontSize: '16px'
					}
				],
				permissionsActions: [{
						name: '私密',
						permission: 'private',
						fontSize: '16px'
					},
					{
						name: '所有人可见',
						permission: 'public',
						fontSize: '16px'
					},
					{
						name: '仅朋友可见',
						permission: 'friends',
						fontSize: '16px'
					}
				],
				observers: [], // Store IntersectionObserver instances
				videoPlayers: {} // Store video player refs by index
			}
		},
		props: {
			location: {
				type: String,
				default: 'center',
			},
			title: {
				type: String,
				default: '时间轴'
			},
			timeLineList: {
				type: Array,
				default: () => []
			},
			showBtn: {
				type: Boolean,
				default: true
			},
			isLoad: {
				type: Boolean,
				default: true
			}
		},
		computed: {
			addTypeClass() {
				let _class = "";
				let arrType = ["left", "right", "center"];
				if (arrType.indexOf(this.location) !== -1 && this.location !== 'center') {
					_class += this.location + "-time-line";
				}
				return _class;
			}
		},
		mounted() {
			this.init();
			this.initializeVideoObservers();
		},
		beforeDestroy() {
			this.cleanupObservers();
		},
		methods: {
			initializeVideoObservers() {
				if (!this.timeLineList || this.timeLineList.length === 0) return;
				this.videoPlayers = {};
				this.timeLineList.forEach((item, index) => {
					if (item.imageList && item.imageList.length > 0 && item.imageList[0].isImage === 0) {
						const videoPlayerRefName = `allPostRef${index}`;
						// Ensure DOM is ready and refs are available
						this.$nextTick(() => {
							const videoPlayerArray = this.$refs[videoPlayerRefName];
							if (videoPlayerArray && videoPlayerArray.length > 0 && videoPlayerArray[0]) {
								this.videoPlayers[index] = videoPlayerArray[0];

								const observer = uni.createIntersectionObserver(this, {
									thresholds: [0.5], // Trigger when 50% visible
									initialRatio: 0,
								});

								observer.relativeToViewport({
										bottom: '0px',
										top: '0px'
									})
									.observe(`.video-wrapper-${index}`, (res) => {
										if (this.videoPlayers[
												index]) { // Check if player ref still exists
											if (res.intersectionRatio >= 0.5) {
												this.videoPlayers[index].play();
											} else {
												this.videoPlayers[index].pause();
											}
										}
									});
								this.observers.push(observer);
							}
						});
					}
				});
			},
			cleanupObservers() {
				this.observers.forEach(observer => observer.disconnect());
				this.observers = [];
				// Also pause any potentially playing videos
				Object.values(this.videoPlayers).forEach(player => {
					if (player && typeof player.pause === 'function') {
						player.pause();
					}
				});
				this.videoPlayers = {};
			},
			getLocation(str) {
				const index = str.indexOf('-');
				return index !== -1 ? str.substring(index + 1) : '';
			},
			openCustomFullScreenVideo(itemId, videoUrl) {
				// 1. Pause the inline video player
				this.pauseVideoById(itemId);

				// 2. Set data for the modal
				this.currentModalVideoSrc = videoUrl;
				this.currentModalVideoId = itemId;
				this.showVideoModal = true;
			},
			closeCustomFullScreenVideo() {
				this.showVideoModal = false;
				this.currentModalVideoSrc = '';
				this.currentModalVideoId = null;
			},
			// 暂停指定视频
			pauseVideoById(itemId) {
				const player = this.videoPlayers[itemId];
				if (player && typeof player.pause === 'function') {
					player.pause();
				}
			},
			fullScreen(index) {
				const item = this.timeLineList[index];
				if (item && item.imageList && item.imageList.length > 0 && item.imageList[0].isImage === 0) {
					this.openCustomFullScreenVideo(index, item.imageList[0].fileUrl);
				}
			},
			previewImage(files, currentIndex) {
				const urls = files.map(file => file.fileUrlOriginal || file.fileUrl); // Prefer original URL for preview
				uni.previewImage({
					urls: urls,
					current: currentIndex,
					fail: (err) => {
						console.error('previewImage fail:', err);
					}
				});
			},
			init() {
				try {
					const res = uni.getSystemInfoSync();
					this.HEIGHT = res.screenHeight;
					this.current = []; // Reset current for animation
					for (let i = 0; i < this.timeLineList.length; i++) {
						this.current.push({
							tag: 'timeline' + i,
							is: 'no'
						});
					}
					if (this.timeLineList.length > 0) {
						this.getScroll();
					}
				} catch (e) {
					// console.error("Error in init:", e);
				}
			},
			onDetail(item, scroll) {
				this.$emit('detailClick', {
					item,
					scroll: scroll || false
				});
			},
			toggleExpand() {
				this.expanded = !this.expanded;
			},
			goToUserPage(userId) {
				uni.navigateTo({
					url: `/pages/user/userInfo?id=${userId}`,
				});
			},
			loadani() {
				for (let i = 0; i < this.result.length; i++) {
					for (let j = 0; j < this.result[i].info.length; j++) {
						if (this.current[j] && this.current[j].is != 'ok') {
							if (this.current[j].tag == this.result[i].info[j].tag &&
								this.result[i].info[j].domTop + 90 < this.HEIGHT) {
								this.current[j].is = 'ok';
								this.sum = j + 1;
							}
						}
					}
					this.result.splice(i, 1);
				}
				if (this.sum == this.timeLineList.length) {
					this.isScroll = false;
				}
			},
			async getScroll() {
				if (!this.isScroll || !this.timeLineList || this.timeLineList.length === 0) {
					return;
				}
				let info = [];
				for (let i = 0; i < this.timeLineList.length; i++) { // <-- 修改
					await this.getNodeList('timeline' + i, i).then(res => {
						if (res) info.push(res);
					}).catch(err => {});
				}
				if (info.length > 0) {
					this.result.push({
						info: info
					});
					this.loadani();
				}
			},
			getNodeList(id, i) {
				return new Promise((resolve, reject) => { // Add reject
					const query = uni.createSelectorQuery().in(this);
					query.select('#' + id).boundingClientRect(data => {
						if (data) { // Check if data is not null
							resolve({
								domInfo: data.height,
								domTop: data.top,
								tag: id
							})
						} else {
							// console.warn(`Node #${id} not found or data is null`);
							resolve(null); // Resolve with null if node not found
						}
					}).exec();
				});
			},
			layoutClass(index) {
				let _class = "";
				if (this.location == 'center' && index % 2 != 0) {
					_class = 'right-info';
				}
				return _class;
			},
			getAlbum() {
				this.$emit('getAlbum')
			},
			toHomePage(userId) {
				uni.navigateTo({
					url: "/pages/user/others/others?userId=" + userId
				})
			},
			openOptionsMenu(item) {
				this.currentItem = item;
				this.showOptionsMenu = true;
			},
			handleOptionSelect(actionItem) {
				if (actionItem.action === 'delete') {
					this.onRemoveItem(this.currentItem.id);
				} else if (actionItem.action === 'edit') {
					const postDataForEdit = JSON.parse(JSON.stringify(this.currentItem));
					uni.navigateTo({
						url: `/pages_sub/user/edit-post/edit-post`,
						events: {
							postUpdated: (data) => {
								this.$emit('refreshData');
							} // Emit to parent (time-axis.vue)
						},
						success: (res) => {
							res.eventChannel.emit('acceptDataFromOpenerPage', {
								data: postDataForEdit
							});
						}
					});
				} else if (actionItem.action === 'setPermissions') {
					this.showPermissionsMenu = true;
				}
			},
			handlePermissionSelect(permissionItem) {
				// Placeholder for API call to update permission
				// updatePostPermission(this.currentItem.id, permissionItem.permission).then(...);
				uni.showToast({
					title: `权限设置为: ${permissionItem.name}`,
					icon: 'none'
				});
			},
			onRemoveItem(idToDelete) {
				uni.showModal({
					title: '',
					content: '确认删除？',
					showCancel: true,
					cancelText: '取消',
					confirmText: '删除',
					success: res => {
						if (res.confirm) {
							deletePost(idToDelete).then(deleteRes => {
								// Emit an event to parent to refresh data
								this.$emit('refreshData');
								uni.showToast({
									title: '删除成功',
									icon: 'success'
								});
							}).catch(err => {
								uni.showToast({
									title: '删除失败',
									icon: 'none'
								});
							});
						}
					}
				});
			},
		},
	}
</script>

<style lang="scss">
	.time-line-wrap {
		width: 100%;
		padding-bottom: 200rpx;
	}

	.up-arrow {
		width: 100%;
		font-size: 80rpx;
		color: #FFFFFF;
	}

	.video-container-wrapper {
		/* New wrapper class */
		/* Add any specific styling for the video wrapper if needed */
		/* e.g., for spacing or borders around the video player */
		margin: 15rpx 0;
		/* Example margin */
	}

	.time-line-wrap {
		font-family: sans-serif;

		.time-line {
			padding: 0 1%;
			padding-right: 5%;

			.time-line-title {
				font-size: 25px;
				font-weight: 800;
				text-align: center;
				margin-bottom: 15px;
			}

			.time-line-dashed {
				left: 15px;
				position: relative;

				.arrow-up {
					position: absolute;
					left: -17px;
					top: -18px;
				}

				.btn {
					position: absolute;
					right: 40rpx;
					top: -20rpx;
					color: #ffffff;
					border-color: #FFFFFF;
					font-weight: 700;
				}
			}

			.time-line-container {
				padding: 0% 1% 20% 1%;
				position: relative;

				&::before {
					content: '';
					position: absolute;
					top: 0;
					left: 0;
					right: 0;
					margin: 0 auto;
					height: 100%;
					width: 1px;
					border-left: 4rpx dashed #F43132;
				}

				.time-line-list {
					width: 100%;
					min-height: 800rpx;

					.time-line-info {
						position: relative;

						.line-info-content {
							will-change: auto;
							width: 43%;
							display: flex;
							flex-direction: column;

							.line-on-round {
								height: 20rpx;
								width: 20rpx;
								border: 4rpx solid #FADB2D;
								border-radius: 50%;
								background: #FADB2D;
								position: absolute;
								left: 0;
								right: 0;
								margin: 0 auto;
								top: 50px;
								z-index: 10;

								&.come-ani {
									animation: come-round .8s ease-in-out;
								}
							}

							.line-on-round-line {
								height: 8rpx;
								width: 30rpx;
								border-top: 2px dashed #F43132;
								position: absolute;
								left: 0;
								right: 0;
								margin: 0 auto;
								top: 50px;
								z-index: 10;

								&.come-ani {
									animation: come-round .8s ease-in-out;
								}
							}

							.info-content-wrap {
								position: relative;

								.info-title {
									min-height: 30px;
									word-break: break-word;
									text-align: right;
									margin: 8px 10px 0px 30px;
									font-size: 34rpx;
									font-weight: 500;
									color: #434245;

									span {
										color: #1177dd;
										font-size: 38rpx;
										font-weight: 600;
										padding-left: 3px;
									}
								}

								.info-content {
									border-radius: 8px;
									padding: 20rpx 30rpx;
									min-height: 40px;
									position: relative;
									background-color: rgba(255, 255, 255, .6);
									box-shadow: 0 0 30rpx rgba(0, 0, 0, 0.05);

									.options-trigger {
										position: absolute;
										right: 15rpx;
										top: 15rpx;
										padding: 5rpx;
										z-index: 11;
									}

									.info-txt {
										font-size: 24rpx !important;
									}

									.info-head {
										display: flex;
										font-size: 24rpx;
										align-items: center;
										margin-bottom: 20rpx;

										.city {
											display: flex;
											align-items: center;

											.name {
												max-width: 250rpx;
												white-space: nowrap;
												overflow: hidden;
												text-overflow: ellipsis;
												margin: 0 10rpx;
												font-size: 30rpx;
											}

											.image {
												width: 20rpx;
											}

											.small {
												color: #666;
												margin-right: 50rpx;
												max-width: 250rpx;
												/*超出部分隐藏*/
												overflow: hidden;
												/*强制在一行*/
												white-space: nowrap;
												/*文本超出部分省略*/
												text-overflow: ellipsis;
											}
										}
									}

									.image-box {
										display: flex;
										align-items: center;
										margin: 15rpx 0;

										.grid-tianzi {
											display: grid;
											/* width: 85px; Removed fixed width */
											width: 100%;
											/* Make it responsive */
											max-width: calc(85px * 2 + 4px);
											/* Max width for 2 columns */
											grid-template-columns: repeat(2, 1fr);
											grid-auto-rows: 1fr;
											gap: 4px;

											.grid-tianzi-item {
												/* width: 85px; Removed fixed width */
												aspect-ratio: 1 / 1;
												overflow: hidden;
											}
										}
									}

									.person {
										font-size: 26rpx;
										width: 100%;
										padding-top: 10rpx;
										display: flex;

										.label {
											width: 120rpx;
										}

										.name-line-box {
											width: calc(100% - 120rpx);
										}
									}
								}

								&.come-ani {
									animation: come-in-left .6s ease-in-out;
								}
							}
						}
					}

					.right-info {
						transform: rotateY(180deg);

						.line-info-content {
							.info-content-wrap {
								.info-title {
									transform: rotateY(180deg);
									text-align: left;
								}

								.info-content {
									.info-txt {
										transform: rotateY(180deg)
									}

									.options-trigger {
										transform: rotateY(180deg);
									}

									.info-head {
										transform: rotateY(180deg);
									}

									.image-box {
										transform: rotateY(180deg);
									}

									.person {
										transform: rotateY(180deg);
									}
								}
							}
						}
					}
				}
			}

			.left-time-line {
				&::before {
					margin: 0;
					left: 15px;
				}

				.time-line-list {
					.time-line-info {
						.line-info-content {
							width: auto;

							.line-on-round {
								left: 0;
								margin: 0;
							}

							.line-on-round-line {
								left: 0;
								margin: 0;
							}

							.info-content-wrap {
								margin-left: 30px;
								margin-bottom: 15px;

								.info-title {
									text-align: left;
								}

								.info-content {
									&::before {
										border-color: transparent #aaa transparent transparent;
										left: -15px;
									}
								}

								&.come-ani {
									animation: come-in-right .6s ease-in-out;
								}
							}
						}
					}
				}
			}

			.right-time-line {
				&::before {
					margin: 0;
					left: 92.8%;
				}

				.time-line-list {
					.time-line-info {
						.line-info-content {
							width: auto;

							.line-on-round {
								left: 90%;
								margin: 0;
							}

							.line-on-round-line {
								left: 90%;
								margin: 0;
							}

							.info-content-wrap {
								margin-right: 55px;
								margin-bottom: 15px;

								.info-content {
									&::before {
										border-color: transparent transparent transparent #aaa;
									}
								}
							}
						}
					}
				}
			}
		}
	}

	@keyframes come-in-left {
		0% {
			transform: translateX(-120%);
		}

		70% {
			transform: translateX(8%);
		}

		100% {
			transform: translateX(0);
		}
	}

	@keyframes come-in-right {
		0% {
			transform: translateX(120%);
		}

		70% {
			transform: translateX(-8%);
		}

		100% {
			transform: translateX(0);
		}
	}

	@keyframes come-round {
		0% {
			transform: scale(0);
			opacity: 0;
		}

		40% {
			opacity: 0;
		}

		60% {
			transform: scale(1.2);
		}

		100% {
			transform: scale(1);
		}
	}
</style>